package com.coovane.bytetrix.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.coovane.bytetrix.common.enumeration.DeleteFlagEnum;
import com.coovane.bytetrix.common.enumeration.EnabledEnum;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * <p>
 * Mybatis-plus配置类
 * </p>
 *
 * @author: Hsu
 * @date: 2022/11/26 22:43
 * @copyright: companyName
 * @see
 * @since 1.8
 */
@Configuration
public class MyBatisPlusConfig extends DefaultIdentifierGenerator implements MetaObjectHandler {

    /**
     * 分页插件，解决total为0的问题，自动识别数据库类型
     *
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor innerInterceptor = new PaginationInnerInterceptor();
        // 溢出总页数后是否进行处理,为true时自动返回第一页
        innerInterceptor.setOverflow(true);
        interceptor.addInnerInterceptor(innerInterceptor);
        return interceptor;
    }

    /**
     * 自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        setFieldValByName("createTime", new Date(), metaObject);
        setFieldValByName("deleteFlag", DeleteFlagEnum.NOT_DELETE.getCode(), metaObject);
        setFieldValByName("enabled", EnabledEnum.FORBIDDEN.getCode(), metaObject);
    }

    /**
     * 自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateTime", new Date(), metaObject);
    }

}
